import { _decorator, Component, instantiate, Node, Prefab } from 'cc';
import { popLevelMap, PopView } from './AppControll';
import { resManger } from '../tools/ResManger';
import { Loader } from '../tools/LoadManger';
import { Singleton, ComSingleton } from '../tools/Singleton';
import { ClubBtnCom } from '../pop/ClubBtnCom';

const { ccclass, property } = _decorator;


@ccclass('PopManager')
export class PopManager extends ComSingleton<PopManager> {
    protected onLoad(): void {
        PopManager._Instance = this;
    }

    ShowPop(pop: PopView, callBack?: (node: Node) => void) {
        let lt = this.node.children;
        let index = popLevelMap.get(pop);
        let nd: Node = null;
        if (lt.length > 0) {
            nd = this.node.children[index];
        }
        if (nd) nd.destroy();
        this.GetPop(pop, (node) => {

            node.name = pop;
            
            if (popLevelMap.get(pop) == 0) {
                node.addComponent(ClubBtnCom);
            }

            this.node.addChild(node);
            
            this.CombLevel();
            if (callBack) callBack(node);
        })
    }

    public GetPop(fileName: string, back: (pop: Node) => void) {
        let pop = null;
        resManger.GetUiPrefabByKey("ui/" + fileName, () => {
            pop = instantiate(Loader.GetUiPrefab("ui/" + fileName));
            if (back) back(pop);
        });
    }

    public CombLevel() {
        let lt = this.node.children;
        for (let i = lt.length - 1; i >= 0; i--) {
             console.log(lt[i].name);
            lt[i].setSiblingIndex(popLevelMap.get(lt[i].name));
        }
    }
}


